@extends('layouts.header')
@section('content')
    <nav class="breadcrumb"><i class="Hui-iconfont">&#xe67f;</i> 首页 <span class="c-gray en">&gt;</span> 检测业务 <span
                class="c-gray en">&gt;</span> <a href="javascript:;" onclick="location.href='/{{config('constant.name_admin')}}/contract/indexPrintPassedCard';">打印合格证</a><span
                class="c-gray en">&gt;</span> 点击进入【{{ $contractInfo->client_name }}】
        <a class="btn btn-primary radius r" style="line-height:1.6em;margin-top:3px"
           href="javascript:location.replace(location.href);"
           title="刷新"><i class="Hui-iconfont">&#xe68f;</i></a>
        <a class="btn btn-primary radius r mr-10" style="line-height:1.6em;margin-top:3px"
           href="javascript:self.location=document.referrer;">
            <i class="Hui-iconfont Hui-iconfont-arrow1-left"></i>&nbsp;&nbsp;返回
        </a>
    </nav>
    <div class="page-container tb_con">
        <div class="cl pd-5 bg-1 bk-gray mt-10">
            <span class="l">
                批量操作：
                <a class="btn btn-primary radius" href="javascript:;" onclick="toPrintPassedCard(this,1)">批量打印</a>

                <a class="btn btn-primary radius" href="javascript:;" onclick="batch_print_passedCard(1)">生成图片</a>
                <!--label class="ml-10"> <input type="checkbox" id="scanFlag">扫码打印模式</label-->
                <a class="btn btn-primary radius" href="javascript:;" id="hege-luru-date">录入试验日期</a>
            </span>
            <span class="r">
                @if(config('constant.app_name') == 'HuiBangJianCe')
                    <span class="mr-20">
                    <label><input type="checkbox" name="print_self_num" >在试验编号下面打印自编号</label>
                </span>
                    <span class="mr-20" id="setPrintToolName">
                    <label><input type="checkbox" name="tool_name2" value="1" >试样名称：<input type="text" class="input-text" style="width: 120px;" id="printBef" placeholder="如:10kv 罗山带" />{自编号}#{工器具名称} </label>
                </span>
                @endif
                <span class="mr-20" id="chosePrintRemote">
                    <label><input type="radio" name="is_remote" value="1" @if(data_get($setting_info,'passedcard_is_remote_print',0) == 1) checked @endif> 远程打印 </label>
                    <label class="ml-10"><input type="radio" name="is_remote" value="0" @if(data_get($setting_info,'passedcard_is_remote_print',0) == 0) checked @endif> 本地打印 </label>
                </span>
                @if(config('constant.app_name') === 'SiChuanDeYang')
                    <span class="mr-20" title="样式1：有二维码； 2：有说明； 3：无二维码，无说明" id="printStyle"></span>
                @endif
                <a class="btn btn-primary radius" href="javascript:;" onclick="passedcard_set()"><i class="Hui-iconfont Hui-iconfont-manage2"></i> 打印设置</a>
            </span>
        </div>
        <div id="card-img" class="hidden">
            <canvas id="canvas" width="270" height="200">浏览器不支持生产图片</canvas>
            <div id="qrcode" class="hidden"></div>
        </div>
        <div class="cl pd-5 bg-1 bk-gray" id="toolGroup"> </div>
        <div class="mt-10">
            <table class="table table-border table-bordered table-bg table-hover table-responsive" id="datatable">
                <thead>
                <tr class="text-c">
                    <th>
                        <input type="checkbox" id="checkAll">
                    </th>
                    <th>条形码</th>
                    <th class="tool_name">样品名称</th>
                    <th>类型</th>
                    <th>检验标准</th>
                    <th>分 类</th>
                    <th>额定电压</th>
                    <th>规格型号</th>
                    <th>样品自编号</th>
                    <th>本次试验日期</th>
                    <th>下次试验日期</th>
                    <th>检验人员姓名</th>
                    <th>检验人员代号</th>
                    <th>审核人</th>
                    <th>结论</th>
                    <th>操作</th>
                </tr>
                </thead>
            </table>
            <div class="f-r mt-10"><input class="input-text" type="text" value="" placeholder="指定页码" id="jumpPage"/></div>
        </div>

    </div>
    <script type="text/javascript" src="/admin/lib/qrcode.min.js"></script>
    <script type="text/javascript" src="/admin/static/myfolder/js/printPassedCard.js?ver={{config('constant.static_res_ver')}}"></script>
    @if(file_exists('admin/static/myfolder/js/passedCardContent_'.config('constant.app_name').'.js'))
        <script type="text/javascript" src="/admin/static/myfolder/js/passedCardContent_{{config('constant.app_name')}}.js?ver={{config('constant.static_res_ver')}}"></script>
    @else
        <script type="text/javascript" src="/admin/static/myfolder/js/passedCardContent_Common.js?ver={{config('constant.static_res_ver')}}"></script>
    @endif
    <script type="text/javascript">
        var setting_sys = @json($setting_sys);
        var table,
            name_admin = "{{config('constant.app_name')}}",
            company_name = "{{ $setting_info->name_pass }}",//合格证上的公司名称
            company_name_pos = "{{ $setting_info->passedcard_company_name_pos }}",//合格证的检测公司名称位置
            tester_count = {{ $setting_info->passedcard_tester_count }},//合格证上的检测人员填写几个人
            is_tester_code = {{ $setting_info->passedcard_is_tester_code }},//合格证上的检测人员名称(真实姓名:0 , 代号:1)
            print_depth = "{{ $setting_info->passedcard_print_depth }}",//合格证的打印深度
            is_remote_print = {{ $setting_info->passedcard_is_remote_print }},//合格证为本机打印或远程打印(本机打印:0 , 远程打印:1)
            pass_remote_ip = "{{ $setting_info->passedcard_remote_ip }}",//合格证的远程打印 ip
            client_name = "{{ $contractInfo->client_name }}",//送检单位
            is_profession_ver = {{ config('constant.is_profession_ver') === true ? 'true' : 'false' }},//系统是否为专业版
            print_style = $.cookie('print_style') ? $.cookie('print_style') : 1, //合格证打印样式，(四川德阳，每个样式不一样)
            have_barcode = setting_sys['passedCard_have_barcode'] == undefined ? 0 : setting_sys['passedCard_have_barcode'], //合格证上是否有二维码
            print_ahead = setting_sys['passedCard_print_ahead'] == undefined ? 0 : setting_sys['passedCard_print_ahead'];//提前打印合格证
        qcode_addr = setting_sys['qcode_addr'] == undefined ? 1 : setting_sys['qcode_addr'];//提前打印合格证

        setprintstyle();  //设置打印样式
        $(function () {
            var Timer,conTimes=0,toolCount={};

            $.fn.dataTable.ext.errMode = 'throw';//datatable抛异常的方式，在console中输出，默认以alert的方式弹出
            table = $('#datatable').DataTable({
                order: [[1, 'asc']],//默认第几个排序
                ordering: true, // 是否排序
                pageLength: 10,
                ajax: "{{URL::full()}}",//客户端分页时，必须写url
                processing: true,//加载数据时候是否显示进度条
                language: {url: '/admin/lib/datatables/dataTables_Chinese_Lang.json'},
                createdRow: function (row, data, dataIndex) {
                    //当tr元素被创建（所有的td元素已经插入进去），或者给tr绑定事件，该回调函数被执行
                    //$(row).addClass( 'text-l' );
                },
                initComplete: function (settings, json) {
                    console.log(1111);
                    let data = json.data;
                    for(let i in data){
                        let tool_name = data[i].tool_name;
                        if (toolCount[tool_name] == undefined) {
                            toolCount[tool_name] = 0;
                        }
                        toolCount[tool_name] += 1;
                    }
                    for(let tool_name in toolCount){
                        $('#toolGroup').append('<span class="ml-10 " onclick="searchTool(this)"><span class="tool-name">'+tool_name+'</span>('+toolCount[tool_name]+')</span>');
                    }
                    //当表格完成加载绘制完成后执行此方法
                    //仅初次表格数据加载完成后执行
                    // $(row).addClass( 'text-c' );
                    $('#datatable_filter input').keypress(function (event) {
                        clearTimeout(Timer);
                        // if(event.which >= 65 && event.which <= 90){
                        // msg = '你按下了 ' + String.fromCharCode(event.which);
                        // layer.msg(msg,{ time:2000 });
                        // }
                        let obj = this;
                        if ($('#scanFlag').prop('checked') && event.which == 13) {
                            conTimes += 1;
                            layer.msg('进入连续打印模式，并触发了回车'+conTimes+'遍');
                            if ($(obj).val().length > 0) {
                                var trDom = $('tbody tr[role]');
                                if (trDom.length == 1) {
                                    $(trDom).find('.print').trigger('click');
                                } else if (trDom.length == 0) {
                                    layer.msg('无记录', {time: 2000});
                                }
                                Timer = setTimeout(function () {
                                    console.log('正在清空搜索内容！');
                                    $(obj).val('').trigger('keyup').val('');
                                }, 500);
                            }
                        }
                    });

                    $(document).keypress(function (event) {
                        $('#datatable_filter input').focus();
                    });
                },
                columns: [
                    { //复选框
                        data: null, class: "text-c res_id",
                        render: function (data, type, row, meta) {
                            return '<input class="hege" type="checkbox" value="' + row.id + '">';
                        }, searchable: false, orderable: false
                    },
                    {
                        data: "bar_code", class: "text-c bar_code",
                        render: function (data, type, row, meta) {
                            return '<span data-key="' + row.key + '">' + data + '</span>';
                        }
                    },
                    {data: "tool_name", class: "text-c tool_name"},
                    {data: "class_name", class: "text-c class_name"},
                    {data: "std_num", class: "text-c std_num"},
                    {data: "class", class: "text-c class"},
                    {data: "voltage", class: "text-c voltage"},
                    {data: "guige_xinghao", class: "text-c guige_xinghao"},
                    {data: "self_num", class: "text-c self_num"},
                    {
                        data: "test_time", class: "text-c test_time",
                        render: function (data, type, row, meta) {
                            if (data === null) return '';
                            var data_arr = data.split('-');
                            if (data_arr.length == 3) {
                                return data_arr[0] + '年' + data_arr[1] + '月' + data_arr[2] + '日';
                            } else {
                                return '';
                            }
                        }
                    },
                    {
                        data: "next_time", class: "text-c next_time",
                        render: function (data, type, row, meta) {
                            if (data === null || row.res === 2) return '-';
                            var data_arr = data.split('-');
                            if (data_arr.length == 3) {
                                return data_arr[0] + '年' + data_arr[1] + '月' + data_arr[2] + '日';
                            } else {
                                return '';
                            }
                        }
                    },
                    {data: "tester_names", class: "text-c tester_names"},
                    {data: "tester_codes", class: "text-c tester_codes"},
                    {data: "audit_man", class: "text-c audit_man"},
                    {
                        data: "res", class: "text-c res",
                        render: function (data, type, row, meta) {
                            if (data === 0) {
                                return '';
                            } else if (data === 1) {
                                return '<span class="label label-primary radius">合格</span>';
                            } else if (data === 2) {
                                return '<span class="label label-danger radius">不合格</span>';
                            }
                        }
                    },
                    {
                        data: null, class: "text-c",
                        render: function (data, type, row, meta) {
                            return '<a class="btn btn-primary-outline radius size-MINI print" href="javascript:;" onclick="print_passedCard(this)">点击打印</a>';
                        }, searchable: false, orderable: false
                    },
                ],
                // columnDefs: [
                //     {targets: [0, 3, 4, 5, 6, 8, 9, 10, 12, 13, 14], searchable: false},//不参与搜索的列
                //     {targets: [0, 3, 4, 5, 6, 8, 9, 10, 12, 13, 14], orderable: false},//禁用排序的列
                //     // { targets: [0,3,4,5,7,8,9,11,12,13], orderable: false },//禁用排序的列
                // ],
            });
            /*  draw  在表格完成绘制后触发*/
            table.on('draw', function () {
                /*var info = table.page.info();
                //如果最后一页仅剩一条记录，而且不是在第一页
                if((info.start == info.end) && info.end > 1){
                    //跳转到上一页
                    $('#datatable_previous').click();
                } */

            });

        });

        /* 查看检测报告 */
        function view_report() {
            layer.msg('功能开发中 ...', {time: 2000});
        }

        /*试验数据  修改*/
        function testData_edit(title, url, id, w, h) {
            layer_show(title, url + '?id=' + id, w, h);
        }

        function batch_check() {
            var doms = $("tbody input:checkbox:checked");
            var l = doms.length;

            layer.msg(l + '', {time: 2000});
        }

        /*表格重新加载*/
        function table_reload(bool) {
            if (bool) {
                //true时，跳到第一页
                table.ajax.reload();
            } else {
                //false时，停留在原来页
                table.ajax.reload(null, false);
            }
        }

        /*单个审核*/
        function check_one(id, status) {
            var index2;

            $.ajax({
                type: 'post',
                url: '/{{config('constant.name_admin')}}/contractDetail/oneCheck',
                // dataType: 'json',
                data: {
                    id: id,
                    status: status,
                    batch_id: '{{ $_GET['id'] }}',
                    _token: '{{ csrf_token() }}',
                },
                success: function (data) {
                    // console.log(data);
                    if (data === '1') {
                        table_reload(0);//0停留在当前页，1回到第一页
                        layer.msg('审核完成!', {icon: 1, time: 1000});
                    } else {
                        layer.msg('操作失败!', {icon: 2, time: 2000});
                    }
                },
                error: function (data) {
                    ajax_error(data);
                },
                beforeSend: function () {
                    //0.4透明度 白色遮罩
                    index2 = layer.load(2, {shade: [0.05, '#000']});
                },
                complete: function () {
                    layer.close(index2);
                },
            });
        }

        /*批量审核 询问框*/
        function check_batch() {
            var doms = $("tbody tr > td:first-child input:checkbox:checked");
            var l = doms.length;
            if (l == 0) {
                layer.msg('请先勾选一条记录', {time: 2000});
                return;
            }

            var checkID = [];//定义一个空数组
            doms.each(function (i) {//把所有被选中的复选框的值存入数组
                checkID[i] = $(this).val();
            });

            layer.confirm('您勾选了 ' + l + ' 条记录', {
                btn: ['批量通过', '批量驳回'], //按钮
                btnAlign: 'c',//按钮居中对齐
                title: '批量审核',
            }, function () {
                check_batch_real(2, checkID);//通过
            }, function () {
                check_batch_real(-1, checkID);//驳回
            });
        }

        /*批量审核*/
        function check_batch_real(status, checkID) {
            var index2;

            $.ajax({
                type: 'post',
                url: '/{{config('constant.name_admin')}}/contractDetail/batchCheck',
                // dataType: 'json',
                data: {
                    status: status,
                    checkID: checkID,
                    batch_id: '{{ $_GET['id'] }}',
                    _token: '{{ csrf_token() }}',
                },
                success: function (data) {
                    // console.log(data);
                    if (data === '1') {
                        table_reload(0);//0停留在当前页，1回到第一页
                        layer.msg('审核完成!', {icon: 1, time: 1000});
                    } else {
                        layer.msg('操作失败!', {icon: 2, time: 2000});
                    }
                },
                error: function (data) {
                    ajax_error(data);
                },
                beforeSend: function () {
                    //0.4透明度 白色遮罩
                    index2 = layer.load(2, {shade: [0.05, '#000']});
                },
                complete: function () {
                    layer.close(index2);
                },
            });
        }

        /*删除*/
        function del(id) {
            var index2;

            layer.confirm('确认要删除吗？', function (index) {
                $.ajax({
                    type: 'GET',
                    url: '/{{config('constant.name_admin')}}/client/del' + '?id=' + id,
                    // dataType: 'json',
                    success: function (data) {
                        // console.log(data);
                        if (data === '1') {
                            table_reload(0);//0停留在当前页，1回到第一页
                            layer.msg('删除成功!', {icon: 1, time: 2000});
                        } else {
                            layer.msg('删除失败!', {icon: 2, time: 2000});
                        }
                    },
                    error: function (data) {
                        ajax_error(data);
                    },
                    beforeSend: function () {
                        //0.4透明度 白色遮罩
                        index2 = layer.load(2, {shade: [0.05, '#000']});
                    },
                    complete: function () {
                        layer.close(index2);
                    },
                });
            });
        }

        /* 合格证设置 */
        function passedcard_set() {
            var title = '合格证设置';
            var url = '/{{config('constant.name_admin')}}/setting/passedCardSet';
            var w = 800;
            var h = 700;
            layer_show(title, url, w, h);
        }

        /*添加*/
        function add(title, url, w, h) {
            layer_show(title, url, w, h);
        }

        // 设置打印样式
        function setprintstyle() {
            var print_styles = @json([1=>'样式一',2=>'样式二',3=>'样式三']);
            var print_str = '打印样式：', checked = '';
            for (index in print_styles) {
                checked = print_style == index ? 'checked' : '';
                print_str += ' <input type="radio" name="print_style" value="' + index + '" ' + checked + '> ' + print_styles[index];
            }
            $('#printStyle').html(print_str);
        }

        // 监听打印样式
        $("input[name=print_style]").on('change', function () {
            print_style = $(this).val();
            $.cookie('print_style', print_style);
        })

        /*打印合格证*/
        function toPrintPassedCard(obj,isBatch=0){
            if (isBatch == 1) { //如果是批量打印
                batch_print_passedCard();
            }else{
                print_passedCard(obj);
            }
        }
        $('input[name=is_remote]','#chosePrintRemote').on('change',function () {
            is_remote_print = parseInt($(this).val());
            connection(); //连接打印机
        })
        //搜索样品名称
        function searchTool(obj) {
            $(obj).css('color', '#5a98de')
            $(obj).siblings().css('color', '#000')
            let toolname = $(obj).find('.tool-name').text(),
                index = $(obj).closest('div.tb_con').find('thead th.tool_name').index();
             console.log(index);
            $('input[type=search]').val(toolname);
            table.column(index).search('^' + toolname + '$', true, false).draw();
        }

        /*批量录入试验日期*/
        $('#hege-luru-date').on('click',function () {
            if($('tbody input:checkbox:checked').length == 0){
                layer.msg('请选择要修改的样品！');
                return false;
            }
            var html = "<div class='ml-20'><input id='pi_date' class='mt-10' type='date' /></div>";
            var indexDate = layer.open({
                type: 1,
                offset: 'auto',
                area: ['300px', '300px'],
                title: "批量录入试验日期", //不显示标题
                content: html, //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
                btn: ['提交', '取消'],
                yes: function (index, layero) {
                    var sample_ids = [];
                    $('tbody input:checkbox:checked').each(function(index){
                        sample_ids.push($(this).val());
                    })
                    var params = {
                        editDate:1,
                        item: 1, //同步项目时间
                        date:$('#pi_date').val(),
                        sample_ids:sample_ids,
                        _form_token:'{{csrf_form_token()}}'
                    };
                    layer.confirm('所有项目日期都会同步！',{
                        btn:['确定','取消'],
                    },function () {
                        luruDate(params);
                    },function () {
                        layer.close(indexDate);
                    })
                },
                cancel: function () {
                    //右上角关闭回调
                }
            });
        })
        function luruDate(params){
            console.log(params);
            ajax('post',"/{{config('constant.name_admin')}}/sampleInfo/indexResLuru",params,function (res) {
                if(res == 0){
                    layer.msg('操作失败！',{icon:2,time:1000},function (){
                        location.reload()
                    });
                }else{
                    layer.msg('操作成功！',{icon:1,time:1000},function (){
                        location.reload()
                    });
                }
            },0);
        }
    </script>
@endsection